import React from 'react';
import { useEffect, useRef, useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { Button, Tag, Input, Popconfirm, Table, Modal, Space, Form, message } from 'antd';
import { getAllUser, register, editUserById, delUserById } from '../api/login'
const User = () => {
    const [messageApi, contextHolder] = message.useMessage();
    useEffect(() => {
        getUsers()
    }, [])
    const getUsers = () => {
        getAllUser().then(res => {
            // console.log(res);
            setDataSource(res.data)
        })
    }
    // MODAL
    const [isModalOpen, setIsModalOpen] = useState(false);

    const handleOk = () => {
        form
            .validateFields()
            .then((values) => {
                let info = values
                info.id = formData.id
                if (modalTitle == '添加用户') {
                    register(info).then(res => {
                        if (res.status == 200) {
                            messageApi.open({
                                type: 'success',
                                content: '添加成功！',
                                duration: 5,
                            });
                            form.resetFields();
                            setIsModalOpen(false);
                            getUsers()
                        } else {
                            messageApi.open({
                                type: 'warning',
                                content: res.message,
                                duration: 5,
                            });
                        }
                    })
                } else {
                    editUserById(info).then(res => {
                        if (res.status == 200) {
                            messageApi.open({
                                type: 'success',
                                content: '编辑成功！',
                                duration: 5,
                            });
                            form.resetFields();
                            setIsModalOpen(false);
                            getUsers()
                        } else {
                            messageApi.open({
                                type: 'warning',
                                content: res.message,
                                duration: 5,
                            });
                        }
                    })
                }
                console.log('验证成功:', values);
            })
            .catch((info) => {
                console.log('验证失败:', info);
            })
            .finally(() => {
                setFormData({})
            })

    };
    const handleCancel = () => {
        console.log(123);
        setIsModalOpen(false);
        form.resetFields();
    };
    // TABLE
    const [modalTitle, setModalTitle] = useState('')
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
    };
    const getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
            <div
                style={{
                    padding: 8,
                }}
                onKeyDown={(e) => e.stopPropagation()}
            >
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        搜索
                    </Button>
                    <Button
                        onClick={() => clearFilters && handleReset(clearFilters)}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        重置
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            confirm({
                                closeDropdown: false,
                            });
                            setSearchText(selectedKeys[0]);
                            setSearchedColumn(dataIndex);
                        }}
                    >
                        过滤
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            close();
                        }}
                    >
                        关闭
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined
                style={{
                    color: filtered ? '#1677ff' : undefined,
                }}
            />
        ),
        onFilter: (value, record) =>
            record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{
                        backgroundColor: '#ffc069',
                        padding: 0,
                    }}
                    searchWords={[searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    });

    const [dataSource, setDataSource] = useState([]);
    const handleAdd = () => {
        setModalTitle('添加用户')
        setIsModalOpen(true);
    };
    const handleEdit = (v) => {
        setFormData(v)
        form.setFieldsValue(v);
        setModalTitle('编辑用户')
        setIsModalOpen(true);
        console.log(formData);
    }
    const handleDelete = (id) => {
        delUserById({ id }).then(res => {
            if (res.status == 200) {
                messageApi.open({
                    type: 'success',
                    content: '删除成功！',
                    duration: 3,
                });
                getUsers()
            } else {
                messageApi.open({
                    type: 'warning',
                    content: res.message,
                    duration: 3,
                });
            }
        })
    };
    const defaultColumns = [
        {
            title: '账号',
            dataIndex: 'account',
            ...getColumnSearchProps('account'),

        },
        {
            title: '昵称',
            dataIndex: 'userName',
            ...getColumnSearchProps('userName'),
        },
        {
            title: 'IP地址',
            dataIndex: 'ip',
            ...getColumnSearchProps('ip'),
        },
        {
            title: '是否被ban',
            dataIndex: 'isBanned',
            render: (_, record) =>
                record.isBanned > 0 ? (
                    <Tag color="red">封禁</Tag>
                ) : <Tag color="blue">正常</Tag>,
        },
        {
            title: '创建时间',
            dataIndex: 'create_time',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) =>
                dataSource.length >= 1 ? (
                    <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                        <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.id)}>
                            <a>删除</a>
                        </Popconfirm>

                        <a onClick={() => handleEdit(record)}>编辑</a>
                    </div>
                ) : null,
        },
    ];
    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,

                title: col.title,

            }),
        };
    });
    // FORM
    const [form] = Form.useForm();
    const [formData, setFormData] = useState({
        account: '',
        create_time: "",
        id: null,
        ip: "",
        isBanned: "",
        passWord: "",
        userName: ""
    });
    return <div>
        {contextHolder}
        <Button
            onClick={handleAdd}
            type="primary"
            style={{
                marginBottom: 16,
            }}
        >
            添加
        </Button>
        {/* 表格 */}
        <Table
            rowKey={record => record.id}
            bordered
            dataSource={dataSource}
            columns={columns}
        />
        {/* 对话框 */}
        <Modal title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
                form={form}
                name="wrap"
                labelCol={{
                    flex: '110px',
                }}
                labelAlign="left"
                labelWrap
                wrapperCol={{
                    flex: 1,
                }}
                colon={false}
                style={{
                    maxWidth: 600,
                }}>
                <Form.Item
                    label="账号"
                    name="account"
                    rules={[
                        {
                            required: true,
                            message: '请勿为空!',
                        }
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="昵称"
                    name="userName"
                    rules={[
                        {
                            required: true,
                            message: '请勿为空!',
                        }
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="密码"
                    name="passWord"
                    rules={[
                        {
                            required: true,
                            message: '请勿为空!',
                        }
                    ]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    </div>
}
export default User